﻿using System;
using System.Collections.Generic;
using System.Text;
using FeCMS.AccessControlModule.handle;
using FeCMS.Common.Interface;
using FeCMS.Common;
using FeCMS.Entity.AccessControlModule;
using FeCMS.CommonFunction;
using System.Collections;

namespace FeCMS.AccessControlModule
{
    public class Manager
    {

        #region 单列

        static Manager instance = null;
        static readonly object padLock = new object();
        /// <summary>
        ///     单件模式返回此类
        /// </summary>
        public static Manager Instance
        {
            get
            {
                lock (padLock)
                {
                    if (instance == null)
                    {
                        instance = new Manager();
                    }
                }
                return instance;
            }
        }

        #endregion


        #region 私有变量


        private PermissionDBEntity perEntity = new PermissionDBEntity();


        #endregion


        #region 构造函数

        /// <summary>
        ///     构造函数
        /// </summary>
        private Manager()
        {
            try
            {
                FeResourceManager rManager = new FeResourceManager();
                perEntity = rManager.Get();
                if (perEntity == null)
                {
                    //TODO:DLK 为空，说明获取不到
                }
            }
            catch(Exception ex)
            {
                //TODO:DLK 异常说明DB文件出错
                throw;
            }
        }

        #region DEBUG
#if DEBUG

        /// <summary>
        ///     用在Debug里虚拟测试数据用的
        /// </summary>
        /// <param name="testEntity"></param>
        public Manager(PermissionDBEntity testEntity)
        {
            perEntity = testEntity;
        }

#endif
        #endregion

        #endregion


        #region 公有方法


        #region 权限判定操作

        /// <summary>
        ///     根据角色检测是否有相应的权限
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="permissionID"></param>
        /// <returns></returns>
        public bool HasPermission(int roleID, int permissionID)
        {
            //为0的权限说明没权限，直接通过
            if (permissionID <= 0)
                return true;

            if (perEntity.Role.ContainsKey(roleID))
            {
                var role = perEntity.Role[roleID];
                if (!role.Enabled)
                {
                    //角色被停用，直接返回False
                    return false;
                }

                var permissions = role.Permission;
                var len = permissions.Length;
                //不在范围内，直接干掉
                if (permissionID < permissions[0] || permissionID > permissions[len - 1])
                {
                    return false;
                }
                return Algorithm.SqDichotomySearch(permissions, len , permissionID);
            }
            return false;
        }

        /// <summary>
        ///     根据管理员检测是否有相应的权限
        /// </summary>
        /// <param name="adminID"></param>
        /// <param name="permissionID"></param>
        /// <returns></returns>
        public bool HasAdminPermission(string adminID, int permissionID)
        {
            //为0的权限说明没权限，直接通过
            if (permissionID <= 0)
                return true;

            if (perEntity.Admin.ContainsKey(adminID))
            {
                //先从角色的权限查起，在查私有权限
                var admin = perEntity.Admin[adminID];
                if (!admin.Enabled)
                {
                    //管理员被禁用，直接拒绝
                    return false;
                }

                for (int i = 0, j = admin.RoleID.Length; i < j; i++)
                {
                    if (HasPermission(admin.RoleID[i], permissionID))
                    {
                        return true;
                    }
                }
                //查找私有权限
                var permissions = perEntity.Admin[adminID].PrivatePermission;
                var len = permissions.Length;
                //不在范围内，直接干掉
                if (permissionID < permissions[0] || permissionID > permissions[len - 1])
                {
                    return false;
                }
                return Algorithm.SqDichotomySearch(permissions, len , permissionID);
            }
            return false;
        }

        /// <summary>
        ///     根据角色获取出所有的权限
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ResponseResult<int[],IErrorCode> GetRolePermission(int roleID)
        {
            if (perEntity.Role.ContainsKey(roleID))
            {
                return new ResponseResult<int[],IErrorCode>(perEntity.Role[roleID].Permission) ;
            }
            return new ResponseResult<int[], IErrorCode>(Function.MergeErrorCode(
                       ErrorCode.ErrorCodeTemplate_Search,
                       ErrorCode.ErrorCodeReason_DoesNotFound,
                       string.Format("RoleID:{0}", roleID)
            ));
        }

        /// <summary>
        ///     根据管理员获取出所有的权限
        /// </summary>
        /// <param name="adminID"></param>
        /// <returns></returns>
        public ResponseResult<int[], IErrorCode> GetAdminPermission(string adminID)
        {
            if (perEntity.Admin.ContainsKey(adminID))
            {
                var admin = perEntity.Admin[adminID];
                //设置多数组长度 为角色权限数量 加 私有权限数量
                List<int[]> array =new List<int[]>();
                for(int i=0,j=admin.RoleID.Length;i<j;i++)
                {
                    var searchReult =SearchRole(admin.RoleID[i]);
                    //角色存在，并且角色没被禁用
                    if(searchReult.Success && searchReult.Result.Enabled)
                    {
                        array.Add(searchReult.Result.Permission);
                    }
                }
                //私有的权限
                array.Add(admin.PrivatePermission);
                //返回所有权限去重的集合
                return new ResponseResult<int[], IErrorCode>(Algorithm.ArrayMergeToRepeat(array.ToArray()));
            }
            return new ResponseResult<int[], IErrorCode>(Function.MergeErrorCode(
                       ErrorCode.ErrorCodeTemplate_Search,
                       ErrorCode.ErrorCodeReason_DoesNotFound,
                       string.Format("AdminID:{0}", adminID)
            ));
        }


        #endregion


        #region 角色操作

        /// <summary>
        ///     给角色添加权限
        /// </summary>
        /// <param name="roleID">角色ID</param>
        /// <param name="permissionID">权限ID</param>
        /// <returns></returns>
        public bool AddRolePermission(int roleID, int[] permissionID)
        {
            if (perEntity.Role.ContainsKey(roleID))
            {
                var permissions = perEntity.Role[roleID].Permission;
                var len =permissions.Length;
                if (len == 0)
                {
                    /*
                     * 之前原来没有权限，
                     * 则把新权限重新排序后存进去
                     * 并触发权限存储
                     */
                    Algorithm.QuickSort(permissionID, 0, len - 1);
                    perEntity.Role[roleID].Permission = permissionID;
                    UpdatePerEntity();
                    return true;
                }
                else
                {
                    //循环逐个插入
                    for (int i = 0,j=permissionID.Length; i <j ; i++)
                    {
                        Algorithm.SqDichotomyInsert(permissions, permissionID[i]);
                    }
                    perEntity.Role[roleID].Permission = permissionID;
                    UpdatePerEntity();
                    return true;
                }

            }

            return false;
        }

        /// <summary>
        ///     添加角色
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public int AddRole(Role role)
        {
            perEntity.Role =CheckNONull(perEntity.Role);
            var handle = PreproccessHandle(new RoleHandle(perEntity.Role));
            return handle.Add(role);
        }

        /// <summary>
        ///     删除角色
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public bool DelRole(int roleID)
        {
            CheckNONull(perEntity.Role);
            var handle = PreproccessHandle(new RoleHandle(perEntity.Role));
            return handle.Del(roleID);
        }

        /// <summary>
        ///     修改角色
        /// </summary>
        /// <param name="roleID">角色ID</param>
        /// <param name="role">角色</param>
        /// <returns></returns>
        public bool EdilRole(int roleID,Role role)
        {
            perEntity.Role=CheckNONull(perEntity.Role);
            var handle = PreproccessHandle(new RoleHandle(perEntity.Role));
            return handle.Edit(roleID, role);
        }


        #region 搜索


        /// <summary>
        ///     搜索角色
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ResponseResult<Role, IErrorCode> SearchRole(int roleID)
        {
            if (perEntity.Role == null)
            {
                //对象为空的错误消息
                var result = ErrorCode.ErrorCodeTemplate_Search;
                result.LongMessage = string.Format(
                    result.LongMessage,
                    "角色",
                    string.Format(ErrorCode.ErrorCodeReason_IsNull.LongMessage,"Role"));

                return new ResponseResult<Role, IErrorCode>(result);
            }
            BaseHandle<Role, int> handle = new RoleHandle(perEntity.Role);
            //处理查询结果
            return ProcessErrorMessage(handle.Search(roleID), string.Format("ID为：{0}的角色", roleID));
        }

        /// <summary>
        ///     获取所有角色
        /// </summary>
        /// <returns></returns>
        public List<Role> GetAllRole()
        {
            return BaseGetAllMethod(
                    perEntity.Role
            );
        }

        /// <summary>
        ///     获取所有的角色[过滤]
        /// </summary>
        /// <param name="filter">过滤方法</param>
        /// <returns></returns>
        public List<Role> GetAllRoleFilter(IFilter<Role> filter)
        {
            return BaseGetAllFilterMethod(
                               perEntity.Role, filter
                       );
        }

        /// <summary>
        ///     获取所有的角色[排序]
        /// </summary>
        /// <param name="comparer">排序方法</param>
        /// <returns></returns>
        public List<Role> GetAllRoleSort(IComparer<Role> comparer)
        {
            return BaseGetAllSortMethod(
                                          perEntity.Role, comparer
                                  );
        }

        /// <summary>
        ///     获取所有的角色[排序,过滤]
        /// </summary>
        /// <param name="comparer">排序方法</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Role> GeTAllRoleSortFilter(IComparer<Role> comparer, IFilter<Role> filter)
        {
            return BaseGetAllSortFilterMethod(
                perEntity.Role,
                comparer,
                filter
                );
        }

        /// <summary>
        ///     获取所有角色[倒序]
        /// </summary>
        /// <returns></returns>
        public List<Role> GetAllRoleDesc()
        {
            return BaseGetAllDescMethod(
                    perEntity.Role
            );
        }

        /// <summary>
        ///     获取所有的角色[倒序，过滤]
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Role> GetAllRoleDescFilter(IFilter<Role> fiter)
        {
            return BaseGetAllDescFilterMethod(
                    perEntity.Role,
                    fiter
                );
        }



        /// <summary>
        ///     根据分页来获取所有角色
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public List<Role> GetAllRole(int site, int page)
        {
            return BaseGetAllMethod(
                    perEntity.Role,
                    site,
                    page
                   );
        }

        /// <summary>
        ///     分页获取所有的角色[过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Role> GetAllRoleFilter(int site, int page,IFilter<Role> filter)
        {
            return BaseGetAllFilterMethod(
                               perEntity.Role,
                               site,
                               page,
                               filter
                       );
        }

        /// <summary>
        ///     分页获取所有角色[排序]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">排序</param>
        /// <returns></returns>
        public List<Role> GetAllRoleSort(int site, int page, IComparer<Role> comparer)
        {
            return BaseGetAllSortMethod(
                  perEntity.Role,
                  site,
                  page,
                  comparer
                );
        }

        /// <summary>
        ///      分页获取所有角色[排序，过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">排序</param>
        /// <param name="filter">过滤</param>
        /// <returns></returns>
        public List<Role> GetAllRoleFilterSort(int site, int page, IComparer<Role> comparer, IFilter<Role> filter)
        {
            return BaseGetAllSortFilterMethod(
                 perEntity.Role,
                 site,
                 page,
                 comparer,
                 filter
                );
        }

        /// <summary>
        ///     根据分页来获取所有角色[倒序]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public List<Role> GetAllRoleDesc(int site, int page)
        {
            return BaseGetAllDescMethod(
                               perEntity.Role,
                               site,
                               page
                              );
        }

        /// <summary>
        ///     根据分页来获取所有角色[倒序,过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Role> GetAllRoleDescFilter(int site, int page, IFilter<Role> filter)
        {
            return BaseGetAllDescFilterMethod(
                perEntity.Role, 
                site, 
                page,
                filter
                );
        }




        #endregion


        /// <summary>
        ///     获取角色总的数量
        /// </summary>
        /// <returns></returns>
        public int GetAllRoleCount()
        {
            return BaseGetAllCountMethod(perEntity.Role);
        }


        #endregion


        #region 权限的操作

        /// <summary>
        ///     添加权限
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        public int AddPermission(Permission permission)
        {
            perEntity.Permission=CheckNONull(perEntity.Permission);
            var handle = PreproccessHandle(new PermissionHandle(perEntity.Permission));
            return handle.Add(permission);
        }

        /// <summary>
        ///     删除权限
        /// </summary>
        /// <param name="permissionID"></param>
        /// <returns></returns>
        public bool DelPermission(int permissionID)
        {
            CheckNONull(perEntity.Permission);
            var handle = PreproccessHandle(new PermissionHandle(perEntity.Permission));
            return handle.Del(permissionID);
        }

        /// <summary>
        ///     修改权限
        /// </summary>
        /// <param name="permissionID">权限ID</param>
        /// <param name="permission">角色</param>
        /// <returns></returns>
        public bool EdilPermission(int permissionID, Permission permission)
        {
            perEntity.Permission=CheckNONull(perEntity.Permission);
            var handle = PreproccessHandle(new PermissionHandle(perEntity.Permission));
            return handle.Edit(permissionID, permission);
        }


        #region 权限的搜索

        /// <summary>
        ///     搜索权限
        /// </summary>
        /// <param name="permissionID"></param>
        /// <returns></returns>
        public ResponseResult<Permission, IErrorCode> SearchPermission(int permissionID)
        {
            if (perEntity.Role == null)
            {
                //对象为空的错误消息
                var result = ErrorCode.ErrorCodeTemplate_Search;
                result.LongMessage = string.Format(
                    result.LongMessage,
                    "权限",
                    string.Format(ErrorCode.ErrorCodeReason_IsNull.LongMessage, "Permission"));

                return new ResponseResult<Permission, IErrorCode>(result);
            }
            BaseHandle<Permission, int> handle = new PermissionHandle(perEntity.Permission);
            //处理查询结果
            return ProcessErrorMessage(handle.Search(permissionID), string.Format("ID为：{0}的权限", permissionID));
        }


        /// <summary>
        ///     获取所有权限
        /// </summary>
        /// <returns></returns>
        public List<Permission> GetAllPermission()
        {
            return BaseGetAllMethod(
                    perEntity.Permission
                   );
        }


        /// <summary>
        ///     获取所有的权限[过滤]
        /// </summary>
        /// <param name="filter">过滤方法</param>
        /// <returns></returns>
        public List<Permission> GetAllPermissionFilter(IFilter<Permission> filter)
        {
            return BaseGetAllFilterMethod(
                               perEntity.Permission, filter
                       );
        }


        /// <summary>
        ///     获取所有的权限[排序]
        /// </summary>
        /// <param name="comparer">排序方法</param>
        /// <returns></returns>
        public List<Permission> GetAllPermissionSort(IComparer<Permission> comparer)
        {
            return BaseGetAllSortMethod(
                                          perEntity.Permission, comparer
                                  );
        }


        /// <summary>
        ///     获取所有的权限[排序,过滤]
        /// </summary>
        /// <param name="comparer">排序方法</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Permission> GeTAllPermissionSortFilter(IComparer<Permission> comparer, IFilter<Permission> filter)
        {
            return BaseGetAllSortFilterMethod(
                perEntity.Permission,
                comparer,
                filter
                );
        }

        /// <summary>
        ///     获取所有权限[倒序]
        /// </summary>
        /// <returns></returns>
        public List<Permission> GetAllPermissionDesc()
        {
            return BaseGetAllDescMethod(
                    perEntity.Permission
            );
        }

        /// <summary>
        ///     获取所有的权限[倒序，过滤]
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Permission> GetAllRoleDescFilter(IFilter<Permission> fiter)
        {
            return BaseGetAllDescFilterMethod(
                    perEntity.Permission,
                    fiter
                );
        }


        /// <summary>
        ///     根据分页来获取所有权限
        /// </summary>
        /// <param name="site">页面大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public List<Permission> GetAllPermission(int site, int page)
        {
            return BaseGetAllMethod(
                    perEntity.Permission,
                    site,
                    page
                   );
        }


        /// <summary>
        ///     分页获取所有的权限[过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Permission> GetAllGetAllPermissionFilter(int site, int page, IFilter<Permission> filter)
        {
            return BaseGetAllFilterMethod(
                               perEntity.Permission,
                               site,
                               page,
                               filter
                       );
        }


        /// <summary>
        ///     分页获取所有权限[排序]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">排序</param>
        /// <returns></returns>
        public List<Permission> GetAllPermissionSort(int site, int page, IComparer<Permission> comparer)
        {
            return BaseGetAllSortMethod(
                  perEntity.Permission,
                  site,
                  page,
                  comparer
                );
        }


        /// <summary>
        ///     分页获取所有权限[排序,过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">排序</param>
        /// <param name="filter">过滤</param>
        /// <returns></returns>
        public List<Permission> GetAllPermissionFilterSort(int site, int page, IComparer<Permission> comparer, IFilter<Permission> filter)
        {
            return BaseGetAllSortFilterMethod(
                 perEntity.Permission,
                 site,
                 page,
                 comparer,
                 filter
                );
        }


        /// <summary>
        ///     根据分页来获取所有权限[倒序]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public List<Permission> GetAllPermissionDesc(int site, int page)
        {
            return BaseGetAllDescMethod(
                               perEntity.Permission,
                               site,
                               page
                              );
        }

        /// <summary>
        ///     根据分页来获取所有权限[倒序,过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Permission> GetAllRoleDescFilter(int site, int page, IFilter<Permission> filter)
        {
            return BaseGetAllDescFilterMethod(
                perEntity.Permission,
                site,
                page,
                filter
                );
        }



        #endregion


        /// <summary>
        ///     获取权限总的数量
        /// </summary>
        /// <returns></returns>
        public int GetAllPermissionCount()
        {
            return BaseGetAllCountMethod(perEntity.Permission);
        }



        #endregion


        #region 管理员操作

        /// <summary>
        ///     给角色添加权限
        /// </summary>
        /// <param name="roleID">角色ID</param>
        /// <param name="permissionID">权限ID</param>
        /// <returns></returns>
        public bool AddAdminRole(int roleID, int[] permissionID)
        {
            if (perEntity.Role.ContainsKey(roleID))
            {
                var permissions = perEntity.Role[roleID].Permission;
                var len = permissions.Length;
                if (len == 0)
                {
                    /*
                     * 之前原来没有权限，
                     * 则把新权限重新排序后存进去
                     * 并触发权限存储
                     */
                    Algorithm.QuickSort(permissionID, 0, len - 1);
                    perEntity.Role[roleID].Permission = permissionID;
                    UpdatePerEntity();
                    return true;
                }
                else
                {
                    //循环逐个插入
                    for (int i = 0, j = permissionID.Length; i < j; i++)
                    {
                        Algorithm.SqDichotomyInsert(permissions, permissionID[i]);
                    }
                    perEntity.Role[roleID].Permission = permissionID;
                    UpdatePerEntity();
                    return true;
                }

            }

            return false;
        }

        /// <summary>
        ///     添加管理员
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public bool AddAdmin(Admin admin)
        {
            perEntity.Admin = CheckNONull(perEntity.Admin);
            AdminHandle handle = new AdminHandle(perEntity.Admin);
            handle.SetDelegateUpdate = UpdatePerEntity;
            return handle.Add(admin);
        }

        /// <summary>
        ///     删除管理员
        /// </summary>
        /// <param name="adminID"></param>
        /// <returns></returns>
        public bool DelAdmin(string adminID)
        {
            perEntity.Admin = CheckNONull(perEntity.Admin);
            BaseHandle<Admin, string> handle = new AdminHandle(perEntity.Admin);
            handle.SetDelegateUpdate = UpdatePerEntity;
            return handle.Del(adminID);
        }

        /// <summary>
        ///     修改管理员
        /// </summary>
        /// <param name="roleID">管理员名</param>
        /// <param name="admin">管理员</param>
        /// <returns></returns>
        public bool EdilAdmin(string adminID, Admin admin)
        {
            perEntity.Admin=CheckNONull(perEntity.Admin);
            BaseHandle<Admin, string> handle = new AdminHandle(perEntity.Admin);
            handle.SetDelegateUpdate = UpdatePerEntity;
            return handle.Edit(adminID, admin);
        }


        #region 管理员搜索

        /// <summary>
        ///     搜索管理员
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ResponseResult<Admin,IErrorCode> SearchAdmin(string adminID)
        {
            if (perEntity.Admin == null)
            {
                /*
                 * 合并错误代码并返回
                 * 对象为空
                 */
                return new ResponseResult<Admin, IErrorCode>(
                    Function.MergeErrorCode(
                       ErrorCode.ErrorCodeTemplate_Search,
                       ErrorCode.ErrorCodeReason_IsNull,
                       "Admin"
                    )
                );
            }
            BaseHandle<Admin, string> handle = new AdminHandle(perEntity.Admin);
            //处理返回结果
            return ProcessErrorMessage(handle.Search(adminID),string.Format("ID为：{0}的管理员",adminID));
        }

        /// <summary>
        ///     获取所有管理员
        /// </summary>
        /// <returns></returns>
        public List<Admin> GetAllAdmin()
        {
            return BaseGetAllMethod(
                    perEntity.Admin
                   );
        }

        /// <summary>
        ///     获取所有的管理员[过滤]
        /// </summary>
        /// <param name="filter">过滤方法</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminFilter(IFilter<Admin> filter)
        {
            return BaseGetAllFilterMethod(
                               perEntity.Admin, filter
                       );
        }

        /// <summary>
        ///     获取所有的管理员[排序]
        /// </summary>
        /// <param name="comparer">排序方法</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminSort(IComparer<Admin> comparer)
        {
            return BaseGetAllSortMethod(
                                          perEntity.Admin, comparer
                                  );
        }


        /// <summary>
        ///     获取所有的管理员[排序,过滤]
        /// </summary>
        /// <param name="comparer">排序方法</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Admin> GeTAllAdminSortFilter(IComparer<Admin> comparer, IFilter<Admin> filter)
        {
            return BaseGetAllSortFilterMethod(
                perEntity.Admin,
                comparer,
                filter
                );
        }

        /// <summary>
        ///     获取所有管理员[倒序]
        /// </summary>
        /// <returns></returns>
        public List<Admin> GetAllAdminDesc()
        {
            return BaseGetAllDescMethod(
                    perEntity.Admin
            );
        }

        /// <summary>
        ///     获取所有的管理员[倒序，过滤]
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Admin> GetAllAdminDescFilter(IFilter<Admin> fiter)
        {
            return BaseGetAllDescFilterMethod(
                    perEntity.Admin,
                    fiter
                );
        }

        /// <summary>
        ///     根据分页来获取所有管理员
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public List<Admin> GetAllAdmin(int site, int page)
        {
            return BaseGetAllMethod(
                    perEntity.Admin,
                    site,
                    page
                   );
        }

        /// <summary>
        ///     分页获取所有的管理员[过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminFilter(int site, int page, IFilter<Admin> filter)
        {
            return BaseGetAllFilterMethod(
                               perEntity.Admin,
                               site,
                               page,
                               filter
                       );
        }

        /// <summary>
        ///     分页获取所有管理员[排序]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">排序</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminSort(int site, int page, IComparer<Admin> comparer)
        {
            return BaseGetAllSortMethod(
                  perEntity.Admin,
                  site,
                  page,
                  comparer
                );
        }

        /// <summary>
        ///     分页获取所有管理员[排序，过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">排序</param>
        /// <param name="filter">过滤</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminFilterSort(int site, int page, IComparer<Admin> comparer, IFilter<Admin> filter)
        {
            return BaseGetAllSortFilterMethod(
                 perEntity.Admin,
                 site,
                 page,
                 comparer,
                 filter
                );
        }


        /// <summary>
        ///     根据分页来获取所有管理员[倒序]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminDesc(int site, int page)
        {
            return BaseGetAllDescMethod(
                               perEntity.Admin,
                               site,
                               page
                              );
        }



        /// <summary>
        ///     根据分页来获取所有管理员[倒序,过滤]
        /// </summary>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<Admin> GetAllAdminDescFilter(int site, int page, IFilter<Admin> filter)
        {
            return BaseGetAllDescFilterMethod(
                perEntity.Admin,
                site,
                page,
                filter
                );
        }





        #endregion


        /// <summary>
        ///     获取管理员总的数量
        /// </summary>
        /// <returns></returns>
        public int GetAllAdminCount()
        {
            return BaseGetAllCountMethod(perEntity.Admin);
        }

        #endregion

        #endregion


        #region 私有方法


        /// <summary>
        ///     更新PerEntity
        /// </summary>
        private void UpdatePerEntity()
        {
            FeResourceManager rManager = new FeResourceManager();
            rManager.Add(perEntity);
        }

        /// <summary>
        ///     获取每个类的主键
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        private int GetIndex(HandleType type)
        {
            switch (type)
            {
                case HandleType.Role:
                    return perEntity.GetRoleID;
                case HandleType.Permission:
                    return perEntity.GetPermissionID;
                default:
                    return -1;
            }
        }

        /// <summary>
        ///     预处理
        /// </summary>
        /// <typeparam name="E">实体</typeparam>
        /// <typeparam name="I">主键类型</typeparam>
        /// <param name="baseHandle">父类</param>
        /// <param name="handle">子类</param>
        private BaseHandle<E, I> PreproccessHandle<E, I>(BaseHandle<E, I> handle)
        {
            handle.SetDelegateUpdate = UpdatePerEntity;
            handle.SetDelegateGetIndex = GetIndex;
            return handle;
        }

        /// <summary>
        ///     处理错误信息
        /// </summary>
        /// <param name="result">响应结果</param>
        /// <param name="msg">附加到后面的详细信息</param>
        /// <returns></returns>
        private ResponseResult<E, IErrorCode> ProcessErrorMessage<E>(ResponseResult<E, IErrorCode> result, string msg)
        {
            if (result.Success != true)
            {
                result.Error.LongMessage = string.Format(result.Error.LongMessage, msg);
            }
            return result;
        }

        #region 基操作方法

        /// <summary>
        ///     防止对象为空
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">源</param>
        /// <returns></returns>
        private Dictionary<K, V> CheckNONull<K, V>(Dictionary<K, V> source)
        {
            if (source == null)
            {
                return  new Dictionary<K, V>(); ;
            }
            return source;
        }

        /// <summary>
        ///     获取出所有的数据信息
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <returns></returns>
        private List<V> BaseGetAllMethod<K, V>(Dictionary<K, V> source)
        {
            List<V> list = new List<V>();

            if (source != null)
            {
                foreach (var s in source)
                {
                    list.Add(s.Value);
                }
            }
            return list;
        }

        

        /// <summary>
        ///     获取出所有的数据信息[过滤输出]
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <returns></returns>
        private List<V> BaseGetAllFilterMethod<K, V>(Dictionary<K, V> source, IFilter<V> fiter)
        {
            if (fiter != null)
            {
                List<V> list = new List<V>();
                if (source != null)
                {
                    foreach (var s in source)
                    {
                        if (fiter.Compare(s.Value))
                        {
                            list.Add(s.Value);
                        }
                    }
                }
                return list;
            }
            else
            {
                return BaseGetAllMethod(source);
            }
        }

        

        /// <summary>
        ///     排序并输出所有数据信息
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="comparer">比较接口</param>
        /// <returns></returns>
        private List<V> BaseGetAllSortMethod<K, V>(Dictionary<K, V> source,IComparer<V> comparer)
        {
            if (source != null)
            {
                List<V> list = new List<V>(source.Values);
                list.Sort(comparer);
                return list;
            }
            return new List<V>();
        }

        /// <summary>
        ///     排序过滤并输出所有的数据信息
        /// </summary>
        /// <typeparam name="K"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="source"></param>
        /// <param name="comparer"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        private List<V> BaseGetAllSortFilterMethod<K, V>(Dictionary<K, V> source,IComparer<V> comparer, IFilter<V> filter)
        {
             if (filter != null)
            {
                if (comparer != null)
                {
                    if (source != null)
                    {
                        List<V> list = new List<V>(source.Values);
                        List<V> newList =new List<V>();
                        foreach(var s in list)
                        {
                            if(filter.Compare(s))
                            {
                                newList.Add(s);
                            }
                        }
                        newList.Sort(comparer);
                        return newList;
                    }
                    return new List<V>();
                }
                return BaseGetAllMethod(source);
            }
            return BaseGetAllSortMethod(source,comparer);

        }

        /// <summary>
        ///     获取出所有的数据信息[倒序输出]
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <returns></returns>
        private List<V> BaseGetAllDescMethod<K, V>(Dictionary<K, V> source)
        {
            if (source != null)
            {
                int i=source.Count;
                V[] list = new V[i];
                foreach(var s in source)
                {
                    list[--i]=s.Value;
                }
                return new List<V>(list);
            }
            return new List<V>();
        }

        /// <summary>
        ///     获取出所有的数据信息[过滤,倒序输出]
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="fiter">过滤器</param>
        /// <returns></returns>
        private List<V> BaseGetAllDescFilterMethod<K, V>(Dictionary<K, V> source, IFilter<V> fiter)
        {
            if (fiter != null)
            {
                if (source != null)
                {
                    int i = source.Count;
                    V[] list = new V[i];
                    foreach (var s in source)
                    {
                        if (fiter.Compare(s.Value))
                        {
                            list[--i] = s.Value;
                        }
                    }
                    //判断有多少数据是被过滤为空的,并生成新的数组返回
                    var len = source.Count - i;
                    if (len == 0)
                    {
                        return new List<V>();
                    }
                    V[] newList = new V[len];
                    Array.Copy(list, i, newList, 0, len);
                    return new List<V>(newList);
                }
                return new List<V>();
            }
            else
            {
                return BaseGetAllDescMethod(source);
            }
        }


        /// <summary>
        ///     分页查找的基类操作
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        private List<V> BaseGetAllMethod<K, V>(Dictionary<K, V> source, int site, int page)
        {
            List<V> list = new List<V>();

            if (source != null)
            {
                int n = 0;
                int minN = site * page;
                int maxN = site * (page + 1);
                foreach (var s in source)
                {
                    n++;
                    if (n > maxN)
                    {
                        break;
                    }
                    if (n > minN)
                    {
                        list.Add(s.Value);
                    }
                }
            }

            return list;
        }

        /// <summary>
        ///     分页查找的基类操作[过滤]
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="flter">过滤器</param>
        /// <returns></returns>
        private List<V> BaseGetAllFilterMethod<K, V>(Dictionary<K, V> source, int site, int page, IFilter<V> flter)
        {
            if (flter != null)
            {
                if (source != null)
                {
                    List<V> list = new List<V>();

                    int n = 0;
                    int minN = site * page;
                    int maxN = site * (page + 1);

                    foreach (var v in source.Values)
                    {
                        if (flter.Compare(v))
                        {
                            n++;
                            if (n > maxN)
                            {
                                break;
                            }
                            if (n > minN)
                            {
                                list.Add(v);
                            }
                        }
                    }
                    return list;
                }
                return new List<V>();
            }
            return BaseGetAllMethod(source, site, page);
        }


        /// <summary>
        ///     排序分页输出所有数据
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="comparer">比较器</param>
        /// <returns></returns>
        private List<V> BaseGetAllSortMethod<K, V>(Dictionary<K, V> source, int site, int page, IComparer<V> comparer)
        {
            if (comparer != null)
            {
                if (source != null)
                {
                    List<V> list = new List<V>(source.Values);
                    List<V> newList = new List<V>();

                    int minN = site * page;
                    int maxN = site * (page + 1);

                    list.Sort(comparer);
                    for (int i = minN, j = list.Count; i < j; i++)
                    {
                        if (i >= maxN)
                        {
                            break;
                        }
                        newList.Add(list[i]);
                    }
                    return newList;
                }
                return new List<V>();
            }
            return BaseGetAllMethod(source, site, page);
        }

        /// <summary>
        ///     分页取数据[过滤，并排序]
        /// </summary>
        /// <param name="source"></param>
        /// <param name="site"></param>
        /// <param name="page"></param>
        /// <param name="?"></param>
        /// <param name="comparer"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        private List<V> BaseGetAllSortFilterMethod<K, V>(Dictionary<K, V> source, int site, int page, IComparer<V> comparer, IFilter<V> filter)
        {
            if (filter != null)
            {
                if (comparer != null)
                {
                    if (source != null)
                    {
                        List<V> list = new List<V>(source.Values);
                        list.Sort(comparer);

                        //算出页码的起始位置
                        int n = 0;
                        int minN = site * page;
                        int maxN = site * (page + 1);

                        List<V> newList = new List<V>();
                        for (int i = 0, j = list.Count; i < j; i++)
                        {
                            if (filter.Compare(list[i]))
                            {
                                n++;
                                if (n > maxN)
                                {
                                    break;
                                }
                                if (n > minN)
                                {
                                    newList.Add(list[i]);
                                }
                            }
                        }
                        return newList;
                    }
                    return new List<V>();
                }
                return BaseGetAllMethod(source, site, page);
            }
            return BaseGetAllSortMethod(source,site, page,comparer);
        }
        

        /// <summary>
        ///     分页查找的基类操作[倒序输出]
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        private List<V> BaseGetAllDescMethod<K, V>(Dictionary<K, V> source, int site, int page)
        {
            if (source != null)
            {
                //根据商数跟余数算出位置起始
                int quotient =source.Count / site;  //商数
                int remainder =source.Count % site; //余数
                int pages = remainder == 0 ? quotient : quotient+1;

                int minN = remainder == 0 ? site * (pages - page - 1) : site * (pages - page - 2) + remainder;
                int maxN = minN + site;

                //计算出数组的大小
                V[] list = new V[site];

                //计算
                int n = 0;
                int i = site;
                foreach (var s in source)
                {
                    n++;
                    if (n > maxN)
                    {
                        break;
                    }
                    if (n > minN)
                    {
                        list[--i] = s.Value;
                    }
                }
                if (i==0 ) //用于判断数组是否被用完
                {
                    return new List<V>(list);
                }
                else
                {
                    var len =site-i;
                    if (len == 0)
                    {
                        return new List<V>();
                    }
                    V[] newList = new V[len];
                    Array.Copy(list, i, newList, 0, len);
                    return new List<V>(newList);
                }
            }

            return new List<V>();
        }

        /// <summary>
        ///     分页查找的基类操作[倒序输出,过滤]
        /// </summary>
        /// <typeparam name="K">键</typeparam>
        /// <typeparam name="V">值</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="site">分页大小</param>
        /// <param name="page">页码</param>
        /// <param name="filter">过滤器</param>
        /// <returns></returns>
        public List<V> BaseGetAllDescFilterMethod<K, V>(Dictionary<K, V> source, int site, int page, IFilter<V> filter)
        {
            if (filter != null)
            {
                if (source != null)
                {
                    List<V> list = new List<V>();
                    //算出页码的起始位置
                    int n = 0;
                    int minN = site * page;
                    int maxN = site * (page + 1);
                    //先把数据存数组里，在倒序输出
                    List<V> valArray = new List<V>(source.Values);
                    for (int i= valArray.Count-1; i>=0; i--)
                    {
                        if (filter.Compare(valArray[i]))
                        {
                            n++;
                            if (n > maxN)
                            {
                                break;
                            }
                            if (n > minN)
                            {
                                list.Add(valArray[i]);
                            }
                        }
                    }
                    return list;
                }
                return new List<V>();
            }
            else
            {
                return  BaseGetAllDescMethod(source, site, page);
            }
        }


        /// <summary>
        ///     获取总数据条数的基方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        private int BaseGetAllCountMethod<K,V>(Dictionary<K,V> t)
        {
            if (t != null)
            {
                return t.Count;
            }
            return 0;
        }

        #endregion

        #endregion

    }
}
